package cn.yj.netty.message.chain;

import cn.yj.netty.common.Encrypt;
import cn.yj.netty.support.test.MessageProtocol;
import cn.yj.netty.utils.EncryptionUtils;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 对内容解密
 *
 * @author 永健
 * @since 2022-02-16 14:10
 */
@Component
public class DecryptHandler extends AbstractMessageChain<MessageProtocol> {

    private static final Logger log = LoggerFactory.getLogger(DecryptHandler.class);

    @Resource(type = DispatchHandler.class)
    @Override
    public AbstractMessageChain setNextChain(AbstractMessageChain nextChain) {
        return super.setNextChain(nextChain);
    }

    @Override
    void doHandler(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) {
        String encrypt = msg.getHeader().getEncrypt();
        log.info("是否需要解密,encrypt={},host={}", encrypt, getHost());
        if (Encrypt.YES.equals(encrypt)) {
            try {
                msg.setBody(EncryptionUtils.decrypt(msg.getBody()));
            } catch (Exception e) {
                e.printStackTrace();
                log.error("解密失败,关闭连接,host={}", encrypt, getHost());
                channelHandlerContext.channel().close();
                return;
            }
        }
        getNextChain().handler(channelHandlerContext, msg);
    }
}
